package com.xjrsoft.common.interceptor;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaStrategy;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.ResponseCode;
import com.xjrsoft.common.model.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * magic-api 接口鉴权
 *
 * @author tzx
 */
@Component
@Slf4j
public class MagicApiRequestInterceptor implements RequestInterceptor {

	/***
	 * 接口请求之前
	 * @param requestEntity
	 * @return
	 */
	@Override
	public Object preHandle(RequestEntity requestEntity) {

		if(!StpUtil.isLogin()){
			log.error("magicApi请求之前未授权导致的未授权退出");
			return R.error(ResponseCode.UN_AUTHORIZED.getCode(),ResponseCode.UN_AUTHORIZED.getMessage());
		}
		SaSession tokenSession = StpUtil.getTokenSession();
		SaSession session = StpUtil.getSession();
		TokenSign tokenSign = session.getTokenSign(StpUtil.getTokenValue());
		String device = tokenSign != null ? tokenSign.getDevice() : null;
		String apiId = requestEntity.getApiInfo().getId();
		if (StrUtil.equalsIgnoreCase(device, "DEVELOPER")) {
			List<String> interfaceIdList = tokenSession.get(GlobalConstant.LOGIN_DEVELOPER_AUTH_LIST_KEY, new ArrayList<>());
			if (CollectionUtils.isEmpty(interfaceIdList) || !interfaceIdList.contains(apiId)) {
				log.error("magicApi请求之前开发者未授权导致的请求未授权推出");
				return R.error(ResponseCode.UN_AUTHORIZED.getCode(),ResponseCode.MAGIC_API_UN_AUTHORIZED.getMessage());
			}
		} else {
			List<Long> roleIds = tokenSession.get(GlobalConstant.LOGIN_USER_ROLE_ID_KEY, new ArrayList<>());
			//非管理员需要进行权限验证
			if (!roleIds.contains(GlobalConstant.SUPER_ADMIN_ROLE_ID)) {
				if (!SaStrategy.me.hasElement.apply(tokenSession.get(GlobalConstant.LOGIN_USER_INTERFACE_AUTH_CODE_KEY, new ArrayList<>()), apiId)) {
					return R.error(ResponseCode.MAGIC_API_UN_AUTHORIZED.getCode(), ResponseCode.MAGIC_API_UN_AUTHORIZED.getMessage());
				}
			}
		}
		return null;
	}


	/**
	 * 接口执行之后
	 * @param requestEntity
	 * @param returnValue
	 * @return
	 */
	@Override
	public Object postHandle(RequestEntity requestEntity, Object returnValue) {
		log.info("{} 执行完毕，返回结果:{}", requestEntity.getApiInfo().getName(), returnValue);
		return null;
	}


}
